import threading
import time
import tkinter as tk

import pygame
from docx import Document
from screeninfo import get_monitors

# 创建Tkinter窗口
root = tk.Tk()
root.overrideredirect(True)
mon = get_monitors()
root.geometry(str(mon[0].width) + 'x' + str(mon[0].height) + '+0+0')
# 创建Text组件
scroll = tk.Scrollbar(root)
text = tk.Text(root, font=('楷体', 20, 'bold'), width=100, height=10, bg='gold')
text.pack(fill=tk.BOTH, expand=True)
scroll.config(command=text.yview)  # 将文本框关联到滚动条上，滚动条滑动，文本框跟随滑动
text.config(yscrollcommand=scroll.set)  # 将滚动条关联到文本框
lyz = '普光老和尚5分26.docx'
for idx, para in enumerate(Document(lyz).paragraphs):
    text.insert(tk.END, para.text)
    text.insert(tk.END, '\n')
times = []
with open('time.txt') as f:
    line = f.readline()
    while line:
        num = list(map(int, line.split(' ')))
        times.append(num)
        line = f.readline()
pygame.mixer.init()
pygame.mixer.music.load('普光老和尚5分26.mp3')
pygame.mixer.music.play()


def highlight_lyrics(text_widget, start_line, end_line, tag_name, foreground_color):
    """
    高亮歌词中指定的行。
    :param text_widget: Tkinter Text组件。
    :param start_line: 高亮开始的行号。
    :param end_line: 高亮结束的行号。
    :param tag_name: 高亮使用的标签名。
    :param foreground_color: 高亮的颜色。
    """
    text_widget.tag_config(tag_name, foreground=foreground_color)
    text_widget.tag_add(tag_name, "{}.0".format(start_line), "{}.0".format(end_line))


end = 0
pa = 0
nLine = 1


def lrc():
    pygame.mixer_music.play()
    # 高亮指定行
    global end
    global nLine
    while True:
        text.tag_delete("highlight")
        highlight_lyrics(text, nLine, nLine + 1, "highlight", "red")
        if 25 == nLine % 26:
            text.yview_moveto(nLine * 0.009)
        time.sleep(times[(nLine - 1) // 10][(nLine - 1) % 10])
        if 1 == end or 90 == nLine:
            exit()
        global pa
        while pa:
            print('pa')
            time.sleep(times[(nLine - 1) // 10][(nLine - 1) % 10])
        nLine += 1


def pause(event):
    print(event)
    global pa
    pa = (pa + 1) % 2
    if 1 == pa:
        pygame.mixer.music.pause()
    elif 0 == pa:
        pygame.mixer.music.unpause()


th = threading.Thread(target=lrc)
th.setDaemon(True)
th.start()


def esc(event):
    print(event)
    global end
    end = 1
    pygame.mixer.stop()
    pygame.mixer.quit()
    root.quit()


def enter(event):
    print(event)
    print(time.time())


root.bind('<Escape>', esc)
root.bind('<space>', pause)

root.mainloop()
